package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.*;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyLingQianMao;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeLingQianMao;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5Apply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5DataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 安心分期（出）&零钱猫 全28 MD5
 *
 * @author WJB
 */
@ApiPlan(productId = "346", type = ApiPlanConvertType.PLAT_PHONE_MD5)
public class ApiPlatLingQianMaoPhoneMd5Convert implements ApiPlatformPhoneMd5ConvertHandler {

    public static final String KEY = "0kgT7oTZpE1xUhE++nE0TQ==";
    public static final String CHANNEL_ID = "axfq";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) {
        ApiPlatDataExchangeLingQianMao data = new ApiPlatDataExchangeLingQianMao();
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiDataExchangeParameter);
        data.setChannel_code(CHANNEL_ID);
        // 手机号MD5
        data.setPhoneMd5(apiDataExchangeParameter.getPhoneMd5());
        //  城市
        data.setCity(apiDataExchangeParameter.getCity());
        // 姓名
        data.setName("默认姓名");
        // 年龄
        data.setAge(apiFieldConverter.getAgeInt());
        //  性别 0-女 1-男 默认1
        String sex = apiDataExchangeParameter.getSex();
        Integer sexChoose = ChooseEq.create()
                .when(sex, "0", 1)
                .when(sex, "1", 0)
                .end(1);
        data.setSex(sexChoose);
        data.setDevice(0);
        //  借款期限
        Integer time = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanTerm(), "1", 3)
                .when(apiDataExchangeParameter.getLoanTerm(), "2", 6)
                .when(apiDataExchangeParameter.getLoanTerm(), "3", 12)
                .when(apiDataExchangeParameter.getLoanTerm(), "4", 24)
                .when(apiDataExchangeParameter.getLoanTerm(), "5", 36)
                .when(apiDataExchangeParameter.getLoanTerm(), "6", 60)
                .end(3);
        data.setLoanTime(time);
        //  职业
        Integer job = ChooseEq.create()
                .when(apiDataExchangeParameter.getCareer(), "1", 0)
                .when(apiDataExchangeParameter.getCareer(), "2", 5)
                .when(apiDataExchangeParameter.getCareer(), "3", 1)
                .when(apiDataExchangeParameter.getCareer(), "4", 2)
                .when(apiDataExchangeParameter.getCareer(), "5", 3)
                .end(0);
        data.setJob(job);
        if (Eq.objectOr(job, 1, 3)) {
            //  营业执照
            Integer bizLicenseYear = ChooseEq.create()
                    .when(apiDataExchangeParameter.getBizLicenseYear(), "1", 0)
                    .when(apiDataExchangeParameter.getBizLicenseYear(), "2", 1)
                    .when(apiDataExchangeParameter.getBizLicenseYear(), "3", 2)
                    .when(apiDataExchangeParameter.getBizLicenseYear(), "4", 3)
                    .end(0);
            if (Eq.object(bizLicenseYear, 3)) {
                data.setCompanyAge(2);
            } else {
                data.setCompanyAge(bizLicenseYear);
            }
            data.setCompanyLicense(bizLicenseYear);
        }
        //  芝麻分
        Integer zhima = ChooseEq.create()
                .when(apiDataExchangeParameter.getSesameCredit(), "1", 1)
                .when(apiDataExchangeParameter.getSesameCredit(), "2", 1)
                .when(apiDataExchangeParameter.getSesameCredit(), "3", 2)
                .when(apiDataExchangeParameter.getSesameCredit(), "4", 3)
                .end(1);
        data.setAliPay(zhima);
        //  公积金
        Integer gongjijin = ChooseEq.create()
                .when(apiDataExchangeParameter.getProvidentFund(), "1", 0)
                .when(apiDataExchangeParameter.getProvidentFund(), "2", 1)
                .when(apiDataExchangeParameter.getProvidentFund(), "3", 2)
                .when(apiDataExchangeParameter.getProvidentFund(), "4", 1)
                .end(0);
        data.setPublicFund(gongjijin);
        //  社保
        Integer shebao = ChooseEq.create()
                .when(apiDataExchangeParameter.getSocialSecurity(), "1", 0)
                .when(apiDataExchangeParameter.getSocialSecurity(), "2", 1)
                .when(apiDataExchangeParameter.getSocialSecurity(), "3", 2)
                .when(apiDataExchangeParameter.getSocialSecurity(), "4", 1)
                .end(0);
        data.setSocialInsureBill(shebao);
        //  房产情况
        Integer house = ChooseEq.create()
                .when(apiDataExchangeParameter.getRealEstateInfo(), "1", 0)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "2", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "3", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "4", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "5", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "6", 2)
                .end(0);
        data.setHaveHouse(house);
        // 信用记录
        Integer creditHistory = ChooseEq.create()
                .when(apiDataExchangeParameter.getOverdue(), "1", 0)
                .when(apiDataExchangeParameter.getOverdue(), "2", 3)
                .when(apiDataExchangeParameter.getOverdue(), "3", 3)
                .end(0);
        data.setTrustInfo(creditHistory);
        //  保单
        Integer baodanIs = ChooseEq.create()
                .when(apiDataExchangeParameter.getInsurancePolicy(), "1", 0)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "2", 1)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "3", 2)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "4", 1)
                .end(0);
        data.setInsureBill(baodanIs);
        //  车产
        Integer car = ChooseEq.create()
                .when(apiDataExchangeParameter.getCarInfo(), "1", 0)
                .when(apiDataExchangeParameter.getCarInfo(), "2", 1)
                .when(apiDataExchangeParameter.getCarInfo(), "3", 1)
                .when(apiDataExchangeParameter.getCarInfo(), "4", 1)
                .end(0);
        data.setHaveCar(car);
        //  贷款金额
        Integer money = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanAmount(), "1", 50000)
                .when(apiDataExchangeParameter.getLoanAmount(), "2", 50000)
                .when(apiDataExchangeParameter.getLoanAmount(), "3", 100000)
                .when(apiDataExchangeParameter.getLoanAmount(), "4", 200000)
                .end(50000);
        data.setLoanAmount(money);
        //  贷款用途
        Integer loanUse = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanPurpose(), "1", 0)
                .when(apiDataExchangeParameter.getLoanPurpose(), "2", 1)
                .when(apiDataExchangeParameter.getLoanPurpose(), "3", 5)
                .when(apiDataExchangeParameter.getLoanPurpose(), "4", 3)
                .when(apiDataExchangeParameter.getLoanPurpose(), "5", 6)
                .when(apiDataExchangeParameter.getLoanPurpose(), "6", 0)
                .end(0);
        data.setApplyPurpose(loanUse);
        //  学历
        Integer qualification = ChooseEq.create()
                .when(apiDataExchangeParameter.getEducationAttainment(), "1", 4)
                .when(apiDataExchangeParameter.getEducationAttainment(), "2", 3)
                .when(apiDataExchangeParameter.getEducationAttainment(), "3", 3)
                .when(apiDataExchangeParameter.getEducationAttainment(), "4", 2)
                .when(apiDataExchangeParameter.getEducationAttainment(), "5", 1)
                .when(apiDataExchangeParameter.getEducationAttainment(), "6", 0)
                .end(4);
        data.setEducation(qualification);
        //  月收入
        Integer monthlySalary = ChooseEq.create()
                .when(apiDataExchangeParameter.getMonthlySalary(), "1", 0)
                .when(apiDataExchangeParameter.getMonthlySalary(), "2", 1)
                .when(apiDataExchangeParameter.getMonthlySalary(), "3", 3)
                .when(apiDataExchangeParameter.getMonthlySalary(), "4", 5)
                .when(apiDataExchangeParameter.getMonthlySalary(), "5", 5)
                .end(0);
        data.setMonthIncome(monthlySalary);
        data.setMarryStatus(1);
        // 工龄
        Integer yearsService = ChooseEq.create()
                .when(apiDataExchangeParameter.getYearsService(), "1", 0)
                .when(apiDataExchangeParameter.getYearsService(), "2", 1)
                .when(apiDataExchangeParameter.getYearsService(), "3", 2)
                .end(0);
        data.setWorkAge(yearsService);
        // 信用卡
        Integer hasCredit = ChooseEq.create()
                .when(apiDataExchangeParameter.getCreditLimit(), "1", 0)
                .when(apiDataExchangeParameter.getCreditLimit(), "2", 1)
                .when(apiDataExchangeParameter.getCreditLimit(), "3", 1)
                .when(apiDataExchangeParameter.getCreditLimit(), "4", 2)
                .when(apiDataExchangeParameter.getCreditLimit(), "5", 3)
                .when(apiDataExchangeParameter.getCreditLimit(), "6", 1)
                .end(0);
        data.setCreditCard(hasCredit);

        AES aes = AES.createEcb(KEY.getBytes());
        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(data));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channel_code", CHANNEL_ID);
            newMap.put("biz_data", dataStr);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) {
        ApiPlatApplyLingQianMao data = new ApiPlatApplyLingQianMao();
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);
        data.setChannel_code(CHANNEL_ID);
        data.setOrganId(apiApplyParameter.dataExchangeApplyId());
        data.setPhone(apiApplyParameter.getPhone());
        //  城市
        data.setCity(apiApplyParameter.getCity());
        // 姓名
        data.setName(apiApplyParameter.getUserName());
        // 年龄
        data.setAge(apiFieldConverter.getAgeInt());
        //  性别 0-女 1-男 默认1
        String sex = apiApplyParameter.getSex();
        Integer sexChoose = ChooseEq.create()
                .when(sex, "0", 1)
                .when(sex, "1", 0)
                .end(1);
        data.setSex(sexChoose);
        data.setDevice(0);
        //  借款期限
        Integer time = ChooseEq.create()
                .when(apiApplyParameter.getLoanTerm(), "1", 3)
                .when(apiApplyParameter.getLoanTerm(), "2", 6)
                .when(apiApplyParameter.getLoanTerm(), "3", 12)
                .when(apiApplyParameter.getLoanTerm(), "4", 24)
                .when(apiApplyParameter.getLoanTerm(), "5", 36)
                .when(apiApplyParameter.getLoanTerm(), "6", 60)
                .end(3);
        data.setLoanTime(time);
        //  职业
        Integer job = ChooseEq.create()
                .when(apiApplyParameter.getCareer(), "1", 0)
                .when(apiApplyParameter.getCareer(), "2", 5)
                .when(apiApplyParameter.getCareer(), "3", 1)
                .when(apiApplyParameter.getCareer(), "4", 2)
                .when(apiApplyParameter.getCareer(), "5", 3)
                .end(0);
        data.setJob(job);
        if (Eq.objectOr(job, 1, 3)) {
            //  营业执照
            Integer bizLicenseYear = ChooseEq.create()
                    .when(apiApplyParameter.getBizLicenseYear(), "1", 0)
                    .when(apiApplyParameter.getBizLicenseYear(), "2", 1)
                    .when(apiApplyParameter.getBizLicenseYear(), "3", 2)
                    .when(apiApplyParameter.getBizLicenseYear(), "4", 3)
                    .end(0);
            if (Eq.object(bizLicenseYear, 3)) {
                data.setCompanyAge(2);
            } else {
                data.setCompanyAge(bizLicenseYear);
            }
            data.setCompanyLicense(bizLicenseYear);
        }
        //  芝麻分
        Integer zhima = ChooseEq.create()
                .when(apiApplyParameter.getSesameCredit(), "1", 1)
                .when(apiApplyParameter.getSesameCredit(), "2", 1)
                .when(apiApplyParameter.getSesameCredit(), "3", 2)
                .when(apiApplyParameter.getSesameCredit(), "4", 3)
                .end(1);
        data.setAliPay(zhima);
        //  公积金
        Integer gongjijin = ChooseEq.create()
                .when(apiApplyParameter.getProvidentFund(), "1", 0)
                .when(apiApplyParameter.getProvidentFund(), "2", 1)
                .when(apiApplyParameter.getProvidentFund(), "3", 2)
                .when(apiApplyParameter.getProvidentFund(), "4", 1)
                .end(0);
        data.setPublicFund(gongjijin);
        //  社保
        Integer shebao = ChooseEq.create()
                .when(apiApplyParameter.getSocialSecurity(), "1", 0)
                .when(apiApplyParameter.getSocialSecurity(), "2", 1)
                .when(apiApplyParameter.getSocialSecurity(), "3", 2)
                .when(apiApplyParameter.getSocialSecurity(), "4", 1)
                .end(0);
        data.setSocialInsureBill(shebao);
        //  房产情况
        Integer house = ChooseEq.create()
                .when(apiApplyParameter.getRealEstateInfo(), "1", 0)
                .when(apiApplyParameter.getRealEstateInfo(), "2", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "3", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "4", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "5", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "6", 2)
                .end(0);
        data.setHaveHouse(house);
        // 信用记录
        Integer creditHistory = ChooseEq.create()
                .when(apiApplyParameter.getOverdue(), "1", 0)
                .when(apiApplyParameter.getOverdue(), "2", 3)
                .when(apiApplyParameter.getOverdue(), "3", 3)
                .end(0);
        data.setTrustInfo(creditHistory);
        //  保单
        Integer baodanIs = ChooseEq.create()
                .when(apiApplyParameter.getInsurancePolicy(), "1", 0)
                .when(apiApplyParameter.getInsurancePolicy(), "2", 1)
                .when(apiApplyParameter.getInsurancePolicy(), "3", 2)
                .when(apiApplyParameter.getInsurancePolicy(), "4", 1)
                .end(0);
        data.setInsureBill(baodanIs);
        //  车产
        Integer car = ChooseEq.create()
                .when(apiApplyParameter.getCarInfo(), "1", 0)
                .when(apiApplyParameter.getCarInfo(), "2", 1)
                .when(apiApplyParameter.getCarInfo(), "3", 1)
                .when(apiApplyParameter.getCarInfo(), "4", 1)
                .end(0);
        data.setHaveCar(car);
        //  贷款金额
        Integer money = ChooseEq.create()
                .when(apiApplyParameter.getLoanAmount(), "1", 50000)
                .when(apiApplyParameter.getLoanAmount(), "2", 50000)
                .when(apiApplyParameter.getLoanAmount(), "3", 100000)
                .when(apiApplyParameter.getLoanAmount(), "4", 200000)
                .end(50000);
        data.setLoanAmount(money);
        //  贷款用途
        Integer loanUse = ChooseEq.create()
                .when(apiApplyParameter.getLoanPurpose(), "1", 0)
                .when(apiApplyParameter.getLoanPurpose(), "2", 1)
                .when(apiApplyParameter.getLoanPurpose(), "3", 5)
                .when(apiApplyParameter.getLoanPurpose(), "4", 3)
                .when(apiApplyParameter.getLoanPurpose(), "5", 6)
                .when(apiApplyParameter.getLoanPurpose(), "6", 0)
                .end(0);
        data.setApplyPurpose(loanUse);
        //  学历
        Integer qualification = ChooseEq.create()
                .when(apiApplyParameter.getEducationAttainment(), "1", 4)
                .when(apiApplyParameter.getEducationAttainment(), "2", 3)
                .when(apiApplyParameter.getEducationAttainment(), "3", 3)
                .when(apiApplyParameter.getEducationAttainment(), "4", 2)
                .when(apiApplyParameter.getEducationAttainment(), "5", 1)
                .when(apiApplyParameter.getEducationAttainment(), "6", 0)
                .end(4);
        data.setEducation(qualification);
        //  月收入
        Integer monthlySalary = ChooseEq.create()
                .when(apiApplyParameter.getMonthlySalary(), "1", 0)
                .when(apiApplyParameter.getMonthlySalary(), "2", 1)
                .when(apiApplyParameter.getMonthlySalary(), "3", 3)
                .when(apiApplyParameter.getMonthlySalary(), "4", 5)
                .when(apiApplyParameter.getMonthlySalary(), "5", 5)
                .end(0);
        data.setMonthIncome(monthlySalary);
        data.setMarryStatus(1);
        // 工龄
        Integer yearsService = ChooseEq.create()
                .when(apiApplyParameter.getYearsService(), "1", 0)
                .when(apiApplyParameter.getYearsService(), "2", 1)
                .when(apiApplyParameter.getYearsService(), "3", 2)
                .end(0);
        data.setWorkAge(yearsService);
        // 信用卡
        Integer hasCredit = ChooseEq.create()
                .when(apiApplyParameter.getCreditLimit(), "1", 0)
                .when(apiApplyParameter.getCreditLimit(), "2", 1)
                .when(apiApplyParameter.getCreditLimit(), "3", 1)
                .when(apiApplyParameter.getCreditLimit(), "4", 2)
                .when(apiApplyParameter.getCreditLimit(), "5", 3)
                .when(apiApplyParameter.getCreditLimit(), "6", 1)
                .end(0);
        data.setCreditCard(hasCredit);

        AES aes = AES.createEcb(KEY.getBytes());
        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(data));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channel_code", CHANNEL_ID);
            newMap.put("biz_data", dataStr);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMd5Apply respApply(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getString("code"), "0")) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        return RespPlatformPhoneMd5Apply.ofSuc();
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }

    @Override
    public RespPlatformPhoneMd5DataExchange respDataExchange(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getString("code"), "0")) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }

        JSONObject resData = jsonObject.getJSONObject("data");
        if (ValidParam.isEmpty(resData)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }

        RespPlatformPhoneMd5DataExchange result = RespPlatformPhoneMd5DataExchange.ofSuc();
        BigDecimal price = resData.getBigDecimal("price");
        String companyName = resData.getString("companyName");
        String productName = resData.getString("productName");
        String logo = resData.getString("productLogo");
        String orderId = resData.getString("organId");

        List<ApiProtocol> protocolList = CollUtils.newArrayList(newList -> {
            //  获取协议
            JSONArray listProtocolResult = resData.getJSONArray("protocolList");
            IteratorUtils.array(listProtocolResult, (protocolResult, index) -> {
                JSONObject protocolObject = listProtocolResult.getJSONObject(index);
                ApiProtocol protocol = new ApiProtocol();
                protocol.setProtocolName(protocolObject.getString("name"));
                protocol.setProtocolUrl(protocolObject.getString("url"));
                newList.add(protocol);
            });
        });

        result.setPrice(price);
        result.setLogoPath(logo);
        result.setDisplayName(companyName);
        result.setProductName(productName);
        result.setApplyId(orderId);
        result.setProtocolList(protocolList);
        return result;
    }

}
